package com.fumasoft.dynamic.utils;

import java.util.Random;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

/**
 * redis工具类.
 *
 * @author jingchen
 * @date 2025/08/30
 */
@Slf4j
@Component
public class RedisUtils {

    private static final Random RANDOM = new Random();

    private static final Integer NUMBER = 100;

    private static final Integer TWO = 2;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private RedisUtils() {
    }

    /**
     * 获取短id.
     *
     * @param tab 根据tab获取短id
     * @return tab对应的短id
     */
    public int getShortId(String tab) {
        String key = "SINDEX." + tab;

        String sid = stringRedisTemplate.opsForValue().get(key);
        if (sid == null) {
            //初始化
            stringRedisTemplate.opsForValue().set(key, "100");
        }
        Long increment = stringRedisTemplate.opsForValue().increment(key);
        if (increment != null) {
            return increment.intValue() * NUMBER + getRandomDigital(TWO);
        } else {
            throw new IllegalStateException("短id初始化失败");
        }
    }

    /**
     * 获取一个随机数.
     *
     * @param count 随机数的长度
     * @return 随机数
     */
    public static int getRandomDigital(int count) {
        String base = "123456789";
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < count; i++) {
            int number = RANDOM.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return Integer.parseInt(sb.toString());
    }

    /**
     * 获取hash值.
     *
     * @param s  key
     * @param s1 value
     * @return value
     */
    public String getHSet(String s, String s1) {
        return (String) stringRedisTemplate.opsForHash().get(s, s1);
    }
}
